<template>
  <div class="card-padding">
    <el-form label-width="100px" :model="searchForm" :rules="rules" ref="searchTmRef">
      <el-form-item label="时间范围" prop="timeRange" >
        <el-col :span="12">
          <el-date-picker
            style="width: 600px"
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
          />
        </el-col>        
      </el-form-item>
      <el-form-item 
      v-for="(item, index) in searchForm.ids"
      :key="index"
      :label="'遥测量' + (index+1)"
      :prop="'ids.' + index + '.name'"
      :rules="rules.name">
        <el-col :span="6">
<!--          <el-select -->
<!--            v-model="item.name" -->
<!--            placeholder="请选择"-->
<!--            clearable-->
<!--            filterable>-->
<!--            <el-option v-for="oneOpt in tcOptions"-->
<!--                       :key="oneOpt.name"-->
<!--                       :label="oneOpt.name +'(' + oneOpt.description + ')'"-->
<!--                       :value="oneOpt.name"></el-option>-->
<!--          </el-select>-->
          <el-cascader
            v-model="item.name"
            :options="tcOptions"
            :props="{ expandTrigger: 'hover' }"
            style="width: 100%"
            clearable
          ></el-cascader>
        </el-col>
        <el-col :span="6" v-for="oneFilter in item.filters" :key="oneFilter.name">
          <div class="d-flex">
            <el-input v-model.number="oneFilter.valuedb" clearable> 
              <template #prepend>
                <el-select 
                style="width:115px"
                v-model="oneFilter.filter" 
                >
                  <el-option v-for="item in filterOpts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
                </el-select>
              </template>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="d-flex">
            <el-button @click="addDomain(index)" v-show="item.filters.length < 2">新增条件</el-button>
            <el-button @click="delDomain(index)" v-show="item.filters.length > 0">删除条件</el-button>
            <el-button @click="delCondition()"><el-icon><Delete/></el-icon>删除一行</el-button>
          </div>          
        </el-col> 
      </el-form-item>
      <el-form-item>
        <el-button 
        v-show="searchForm.ids.length < 6"
        type="default" 
        @click="addCondition">
          <el-icon><Plus/></el-icon>
          增加查询遥测量</el-button>
          <SearchButton @click="handleSearch"></SearchButton>
          <ResetButton @click="handleReset"></ResetButton>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import SearchButton from '@/components/Buttons/SearchButton.vue';
import ResetButton from '@/components/Buttons/ResetButton.vue';
import { useTmStore } from '@/stores/tm-module';
import { fetchAllTmList } from '@/api/loads-api'
import { onBeforeMount, ref } from 'vue'
import moment from 'moment'
import { deepClone } from '@/comm/index.js'

const searchTmRef = ref(null)
const tmStore = useTmStore()
const emit = defineEmits(['search', 'reset'])

let searchForm = ref({
  timeRange: '',
  ids: [{name: '', filters: []}]
})
const filterOpts = ref([
  {
    label: '大于',
    value: 0
  },
  {
    label: '小于',
    value: 1
  },
  {
    label: '等于',
    value: 2
  }
])
const rules = {
  timeRange: [
   { required: true, message: '必填项', trigger: 'blur' }
  ],
  name: { required: true, message: '必填项', trigger: 'blur' }
}
let tcOptions = ref([])

const addCondition = () => {
  searchForm.value.ids.push({
    name: '',
    filters: []
  })
}
const delCondition = () => {
  searchForm.value.ids.pop()
}
const addDomain = (index) => {
  searchForm.value.ids[index]?.filters.push({
    valuedb: '', filter: 0
  })
}
const delDomain = (index) => {
  searchForm.value.ids[index]?.filters.pop()
}
const handleSearch = async() => {
  let reqJosn = deepClone(searchForm.value)
  await searchTmRef.value.validate((valid, fields) => {
    if(valid) {
      let start = moment(reqJosn.timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
      let end = moment(reqJosn.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
      for( const item of reqJosn.ids) {
        const name = item.name[1].toString()
        item.name = name
      }
      reqJosn = { ...reqJosn, ...{start, end} }
      delete reqJosn.timeRange
      tmStore.setSearchForm(reqJosn)
      emit('search')
    }
  })
}

const handleReset = () => {
  searchForm.value = {
    timeRange: '',
    ids: [{name: '', filters: []}]
  }
  emit('reset')
}

const searchTm = () => {
  fetchAllTmList({}, (response) => {
      const resData = response.data.excel.sheets
      let tcList = []
      for (let i = 0; i < resData.length; i++) {
        let rootTree = {
          label: resData[i].name ,
          value: resData[i].name,
          children: []
        }
        const rows = resData[i].rows
        for (let j = 1; j < rows.length; j++) {
          const row = rows[j]
          const childTree = {
            label: row.name + '（' + row.description + '）',
            value: row.name
          }
          rootTree.children.push(childTree)
        }
        tcList.push(rootTree)
      }
      tcOptions.value = tcList
    }, (error) => {
      console.log("error:", error)
    })
}

onBeforeMount(() => {
  searchTm()
})
</script>

<style lang="scss" scoped>

</style>